package cn.net.xyan.facerecognition.utils

import org.bytedeco.javacpp.BytePointer
import org.bytedeco.javacpp.opencv_core
import org.bytedeco.javacv.Frame
import java.awt.image.BufferedImage
import org.bytedeco.javacv.OpenCVFrameConverter
import java.awt.image.DataBufferByte
import java.nio.ByteBuffer


fun BufferedImage.convert2Gray(): BufferedImage {
    val image = BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY)
    val g = image.graphics
    g.drawImage(this, 0, 0, null)
    g.dispose()
    return image
}

fun BufferedImage.convert2Mat(): opencv_core.Mat {
    val image = when (type) {
        BufferedImage.TYPE_BYTE_GRAY -> this
        else -> convert2Gray()
    }

    val data = (image.raster.dataBuffer as DataBufferByte).data

//    val frame = Frame(width,height,8,1)
//
//    frame.image = arrayOf(ByteBuffer.wrap(data))
//
//    val converter = OpenCVFrameConverter.ToMat()
//
//    val mat = converter.convert(frame)

    val mat = opencv_core.Mat(height,width,opencv_core.CV_8UC1)

    mat.data(BytePointer(ByteBuffer.wrap(data)))

    return mat
}